package org.leaf.green.b2b

import org.leaf.green.admin.RecordType

import org.springframework.transaction.annotation.*
import org.hibernate.FetchMode as FM

class StockInAjaxService {

    static transactional = true

    //purchase detail
    @Transactional(readOnly = true)
    def purchaseDetail(Long Id) {
        log.info("Id=${Id}")
        def purchase_serialNumber = PurchaseDetail.withCriteria(uniqueResult:true){

            createAlias 'purchase', 'p'

            projections{
                property("p.serialNumber")
                property("serialNumber")
            }

            fetchMode "purchase", FM.JOIN

            eq("id", Id)
        }
        log.info("${purchase_serialNumber}")
        return "${purchase_serialNumber[0]}-${purchase_serialNumber[1]}"
    }

    //dealer, [$recordType.name]$serialNumber-$name
    @Transactional(readOnly = true)
    def dealer(Long Id) {
        def dealer = Dealer.withCriteria(uniqueResult:true){

            createAlias 'recordType', 'rt'
            
            projections{
                property("serialNumber")
                property("name")
                property("rt.name")
            }

            fetchMode "recordType", FM.JOIN
            
            eq("id", Id)
        }

        return "[${dealer[2]}]${dealer[0]}-${dealer[1]}"
    }

    //product,$serialNumber-$name
    @Transactional(readOnly = true)
    def product(Long Id) {
        def product = Product.withCriteria(uniqueResult:true){
            projections{
                property("serialNumber")
                property("name")
            }
            eq("id", Id)
        }

        return "${product[0]}-${product[1]}"
    }

    //warehouse
    @Transactional(readOnly = true)
    def warehouse(term) {
        def warehouse = Warehouse.withCriteria(){

            projections{
                property('id')
                property("serialNumber")
                property("name")
            }
            
            eq("isActive", true)
            or{
                ilike("serialNumber", term + "%")
                ilike("name", "%"+term + "%")
            }

            maxResults(10)

            order("serialNumber", "asc")
        }

        return warehouse
    }

    //purchase detail
    @Transactional(readOnly = true)
    def purchaseDetailQuantity(Long Id) {
        log.info("Id=${Id}")
        def purchase_detail_quantity = PurchaseDetail.withCriteria(uniqueResult:true){

            projections{
                property("quantity")
            }

            eq("id", Id)
        }
        log.info("${purchase_detail_quantity}")
        return "${purchase_detail_quantity}"
    }

    
}
